<template>
  <div class="cropper-content">
    <el-row :gutter="10" style="height: 400px;">
      <el-col :span="12">
        <vue-cropper ref="cropperRef" v-bind="cropperOption" :img="state.img" @real-time="handleRealTime"/>
      </el-col>
      <el-col :span="12" class="flex-center">
        <slot name="preview" :image="state.imageBase64">
          <el-image :src="state.imageBase64" :preview-src-list="[state.imageBase64]"></el-image>
        </slot>
      </el-col>
    </el-row>
    <div style="margin-top: 20px;display: flex;">
      <el-upload ref="uploadRef" :limit="1" :on-change="handleChange" :on-exceed="handleExceed" :auto-upload="false" :show-file-list="false">
        <el-button>
          上传
          <el-icon><UploadFilled /></el-icon>
        </el-button>
      </el-upload>
      <el-button-group style="margin-left: 20px;">
        <el-button :icon="Plus" @click="handleScale(1)"/>
        <el-button :icon="Minus" @click="handleScale(-1)"/>
        <el-button :icon="RefreshLeft" @click="handleRotate(-1)"/>
        <el-button :icon="RefreshRight" @click="handleRotate(1)"/>
      </el-button-group>
    </div>
  </div>
</template>

<script setup>
import { reactive, computed, ref } from 'vue'
import 'vue-cropper/dist/index.css'
import { VueCropper }  from "vue-cropper";
import { genFileId, ElMessage } from 'element-plus'
import { UploadFilled, Plus, Minus, RefreshLeft, RefreshRight } from '@element-plus/icons-vue' 

const props = defineProps({
  option: {
    type: Object,
    default() {
      return {}
    }
  }
})

const cropperRef = ref(null)
const uploadRef = ref(null)

const state = reactive({
  img: props.option.img,
  previewData: {},
  imageBase64: null
})

const cropperOption = computed(() => {
  return {
    outputSize: 0.5,
    outputType: 'png',
    autoCrop: true,
    ...props.option,
  }
})


let timer = null
const handleRealTime = (data) => {
  state.previewData = data

  clearTimeout(timer)
  timer = setTimeout(() => {
    cropperRef.value.getCropData(base64 => {
      state.imageBase64 = base64
    })
  }, 500)
}

const handleChange = (file, files) => {
  if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(file.name )) {
    return ElMessage.warngin('图片格式不正确,仅支持（jpg|jpeg|png|bmp）')
  }

  const reader = new FileReader();
  reader.onload = (evt) => {
    state.img = evt.target.result
  };
  reader.readAsDataURL(file.raw);
}

const handleExceed = (files) => {
  uploadRef.value.clearFiles()
  const file = files[0]
  file.uid = genFileId()
}

const handleScale = (scale) => {
  cropperRef.value.changeScale(0.5 * scale)
}

const handleRotate = (rotate) => {
  if (rotate > 1) {
    cropperRef.value.rotateRight()
  } else {
    cropperRef.value.rotateLeft()
  }
}

</script>

<style scoped lang="scss">
.flex-center{
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>

